import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ConfigService } from '@nestjs/config';
import { BaseService } from '@wwjCommon/base/base.service';
import { CacheService } from '@wwjCommon/cache/cache.service';
import { LoggingService } from '@wwjCommon/logging/logging.service';
import { UploadService } from '@wwjVendor/upload/upload.service';
import { PayService } from '@wwjVendor/pay/pay.service';
import { SmsService } from '@wwjVendor/sms/sms.service';
import { NoticeService } from '@wwjVendor/notice/notice.service';

@Injectable()
export class RoleService extends BaseService<any> {
  private readonly logger = new Logger(RoleService.name);

  constructor(
    @InjectRepository(Object)
    protected readonly repository: Repository<any>,
    private readonly cacheService: CacheService,
    private readonly configService: ConfigService,
    private readonly loggingService: LoggingService,
    private readonly uploadService: UploadService,
    private readonly payService: PayService,
    private readonly smsService: SmsService,
    private readonly noticeService: NoticeService,
  ) {
    super(repository);
  }

  /**
   * getPage
   * 对应 PHP: RoleService_admin::getPage()
   * 逻辑类型: undefined - undefined
   */
  async getPage(data: any[]) {
    // 基于PHP真实逻辑: getPage
    // PHP原文: $where = [['site_id', '=', $this->site_id]];         if(isset($data['role_name']) && $data['role_name'] !== '') {             $where[] = ['role_name',...
const where = [['site_id', '=', this.site_id]];
        if(typeof data.role_name) && data.role_name !== '') {
            where[] = ['role_name', 'like', "%".this.model.handelSpecialCharacter(data.role_name) + '%"];
  }

  /**
   * getInfo
   * 对应 PHP: RoleService_admin::getInfo()
   * 逻辑类型: undefined - undefined
   */
  async getInfo(role_id: number) {
    // 基于PHP真实逻辑: getInfo
    // PHP原文: return $this->model->append(['status_name'])->findOrEmpty($role_id)->toArray();     }      /**      * 获取站点下的所有权限      * @return array      * @throws D...
return this.model.append(.status_name).findOrEmpty(role_id).toArray(];
    }

    /**
     * 获取站点下的所有权限
     * @return * @throws DataNotFoundBusinessException
     * @throws DbBusinessException
     * @throws ModelNotFoundBusinessException
     */
    async getAll()
    {
        const where = [
            ['site_id', '=', this.site_id],
            ['status', '=', 1)
        ];
        const site_role_all = this.model.where(where).field('role_id,role_name,rules,status,create_time').select().toArray(];
        foreach (site_role_all as key => value) {
            site_role_all[key].disabled = false;
  }

  /**
   * getAll
   * 对应 PHP: RoleService_admin::getAll()
   * 逻辑类型: undefined - undefined
   */
  async getAll() {
    // 基于PHP真实逻辑: getAll
    // PHP原文: $where = array(             ['site_id', '=', $this->site_id],             ['status', '=', 1]         );         $site_role_all = $this->model->where($...
const where = [
            ['site_id', '=', this.site_id],
            ['status', '=', 1)
        ];
        const site_role_all = this.model.where(where).field('role_id,role_name,rules,status,create_time').select().toArray(];
        foreach (site_role_all as key => value) {
            site_role_all[key].disabled = false;
  }

  /**
   * add
   * 对应 PHP: RoleService_admin::add()
   * 逻辑类型: undefined - undefined
   */
  async add(data: any[]) {
    // 基于PHP真实逻辑: add
    // PHP原文: $data['create_time'] = time();         $data['app_type'] = $this->app_type;         $data['site_id'] = $this->site_id;         $this->model->save($dat...
data.create_time = time(];
        data.app_type = this.app_type;
        data.site_id = this.site_id;
        this.model.save(data);
        Cache.tag(self.cache_tag_name.this.site_id).clear(];
        return true;
    }

    /**
     * 更新权限
     * @param int role_id
     * @param data
     * @return true
     */
    async edit(int role_id, data){
        const where = [
            ['role_id', '=', role_id],
            ['site_id', '=', this.site_id),
        ];
        data.update_time = time(];
        this.model.update(data, where);
        Cache.tag(self.cache_tag_name.this.site_id).clear(];
        return true;

    }

    /**
     * 修改状态
     * @param data
     * @return SysRole
     */
    async modifyStatus(data)
    {
        return this.model.where([
            [ 'role_id', '=', data[ 'role_id' ] ],
            [ 'site_id', '=', this.site_id )
        )).update([ status: data[ 'status' ) )];
    }

    /**
     * 获取模型对象
     * @param int site_id
     * @param int role_id
     * @return mixed
     */
    async find(int site_id, int role_id){
        const where = [
            ['role_id', '=', role_id],
            ['site_id', '=', site_id),
        ];
        const role = this.model.where(where).findOrEmpty(];
        if (role.isEmpty())
            throw new AdminBusinessException('USER_ROLE_NOT_EXIST');
        return role;
    }

    /**
     * 删除权限(saas应该不允许删除)
     * @param int role_id
     * @return mixed
     * @throws DbBusinessException
     */
    async del(int role_id){
        const role = this.find(this.site_id, role_id];
        if(SysUserRole.where([['role_ids', 'like',['%"'.role_id + '"%']))).count() > 0)
            throw new AdminBusinessException('USER_ROLE_NOT_ALLOW_DELETE'];
        const res = role.delete();
        Cache.tag(self.cache_tag_name.this.site_id).clear(];
        return res;

    }

    /**
     * 获取角色id为健名,角色名为键值的数据
     * @param int site_id
     * @return mixed|string
     */
    async getColumn(int site_id){
        const cache_name = 'role_column_'.site_id;
        return cache_remember(
            cache_name,
            function() use(site_id) {
                const where = [
                    ['site_id', '=', site_id]
                ];
                return this.model.where(where).column('role_name', 'role_id');
  }

  /**
   * edit
   * 对应 PHP: RoleService_admin::edit()
   * 逻辑类型: undefined - undefined
   */
  async edit(role_id: any[], data: any[]) {
    // 基于PHP真实逻辑: edit
    // PHP原文: $where = array(             ['role_id', '=', $role_id],             ['site_id', '=', $this->site_id],         );         $data['update_time'] = time()...
const where = [
            ['role_id', '=', role_id],
            ['site_id', '=', this.site_id),
        ];
        data.update_time = time(];
        this.model.update(data, where);
        Cache.tag(self.cache_tag_name.this.site_id).clear(];
        return true;

    }

    /**
     * 修改状态
     * @param data
     * @return SysRole
     */
    async modifyStatus(data)
    {
        return this.model.where([
            [ 'role_id', '=', data[ 'role_id' ] ],
            [ 'site_id', '=', this.site_id )
        )).update([ status: data[ 'status' ) )];
    }

    /**
     * 获取模型对象
     * @param int site_id
     * @param int role_id
     * @return mixed
     */
    async find(int site_id, int role_id){
        const where = [
            ['role_id', '=', role_id],
            ['site_id', '=', site_id),
        ];
        const role = this.model.where(where).findOrEmpty(];
        if (role.isEmpty())
            throw new AdminBusinessException('USER_ROLE_NOT_EXIST');
        return role;
    }

    /**
     * 删除权限(saas应该不允许删除)
     * @param int role_id
     * @return mixed
     * @throws DbBusinessException
     */
    async del(int role_id){
        const role = this.find(this.site_id, role_id];
        if(SysUserRole.where([['role_ids', 'like',['%"'.role_id + '"%']))).count() > 0)
            throw new AdminBusinessException('USER_ROLE_NOT_ALLOW_DELETE'];
        const res = role.delete();
        Cache.tag(self.cache_tag_name.this.site_id).clear(];
        return res;

    }

    /**
     * 获取角色id为健名,角色名为键值的数据
     * @param int site_id
     * @return mixed|string
     */
    async getColumn(int site_id){
        const cache_name = 'role_column_'.site_id;
        return cache_remember(
            cache_name,
            function() use(site_id) {
                const where = [
                    ['site_id', '=', site_id]
                ];
                return this.model.where(where).column('role_name', 'role_id');
  }

  /**
   * modifyStatus
   * 对应 PHP: RoleService_admin::modifyStatus()
   * 逻辑类型: undefined - undefined
   */
  async modifyStatus(data: any) {
    // 基于PHP真实逻辑: modifyStatus
    // PHP原文: return $this->model->where([             [ 'role_id', '=', $data[ 'role_id' ] ],             [ 'site_id', '=', $this->site_id ]         ])->update([ '...
return this.model.where([
            [ 'role_id', '=', data[ 'role_id' ] ],
            [ 'site_id', '=', this.site_id )
        )).update([ status: data[ 'status' ) )];
    }

    /**
     * 获取模型对象
     * @param int site_id
     * @param int role_id
     * @return mixed
     */
    async find(int site_id, int role_id){
        const where = [
            ['role_id', '=', role_id],
            ['site_id', '=', site_id),
        ];
        const role = this.model.where(where).findOrEmpty(];
        if (role.isEmpty())
            throw new AdminBusinessException('USER_ROLE_NOT_EXIST');
        return role;
    }

    /**
     * 删除权限(saas应该不允许删除)
     * @param int role_id
     * @return mixed
     * @throws DbBusinessException
     */
    async del(int role_id){
        const role = this.find(this.site_id, role_id];
        if(SysUserRole.where([['role_ids', 'like',['%"'.role_id + '"%']))).count() > 0)
            throw new AdminBusinessException('USER_ROLE_NOT_ALLOW_DELETE'];
        const res = role.delete();
        Cache.tag(self.cache_tag_name.this.site_id).clear(];
        return res;

    }

    /**
     * 获取角色id为健名,角色名为键值的数据
     * @param int site_id
     * @return mixed|string
     */
    async getColumn(int site_id){
        const cache_name = 'role_column_'.site_id;
        return cache_remember(
            cache_name,
            function() use(site_id) {
                const where = [
                    ['site_id', '=', site_id]
                ];
                return this.model.where(where).column('role_name', 'role_id');
  }

  /**
   * findRecord (原方法名: find)
   * 对应 PHP: RoleService_admin::find()
   * 逻辑类型: undefined - undefined
   * 注意: 为避免与BaseService方法冲突，已重命名
   */
  async findRecord(site_id: number, role_id: number) {
    // 基于PHP真实逻辑: find
    // PHP原文: $where = array(             ['role_id', '=', $role_id],             ['site_id', '=', $site_id],         );         $role = $this->model->where($where)...
const where = [
            ['role_id', '=', role_id],
            ['site_id', '=', site_id),
        ];
        const role = this.model.where(where).findOrEmpty(];
        if (role.isEmpty())
            throw new AdminBusinessException('USER_ROLE_NOT_EXIST');
        return role;
    }

    /**
     * 删除权限(saas应该不允许删除)
     * @param int role_id
     * @return mixed
     * @throws DbBusinessException
     */
    async del(int role_id){
        const role = this.find(this.site_id, role_id];
        if(SysUserRole.where([['role_ids', 'like',['%"'.role_id + '"%']))).count() > 0)
            throw new AdminBusinessException('USER_ROLE_NOT_ALLOW_DELETE'];
        const res = role.delete();
        Cache.tag(self.cache_tag_name.this.site_id).clear(];
        return res;

    }

    /**
     * 获取角色id为健名,角色名为键值的数据
     * @param int site_id
     * @return mixed|string
     */
    async getColumn(int site_id){
        const cache_name = 'role_column_'.site_id;
        return cache_remember(
            cache_name,
            function() use(site_id) {
                const where = [
                    ['site_id', '=', site_id]
                ];
                return this.model.where(where).column('role_name', 'role_id');
  }

  /**
   * del
   * 对应 PHP: RoleService_admin::del()
   * 逻辑类型: undefined - undefined
   */
  async del(role_id: number) {
    // 基于PHP真实逻辑: del
    // PHP原文: $role = $this->find($this->site_id, $role_id);         if(SysUserRole::where([['role_ids', 'like',['%"'.$role_id.'"%']]])->count() > 0)             th...
const role = this.find(this.site_id, role_id];
        if(SysUserRole.where([['role_ids', 'like',['%"'.role_id + '"%']))).count() > 0)
            throw new AdminBusinessException('USER_ROLE_NOT_ALLOW_DELETE'];
        const res = role.delete();
        Cache.tag(self.cache_tag_name.this.site_id).clear(];
        return res;

    }

    /**
     * 获取角色id为健名,角色名为键值的数据
     * @param int site_id
     * @return mixed|string
     */
    async getColumn(int site_id){
        const cache_name = 'role_column_'.site_id;
        return cache_remember(
            cache_name,
            function() use(site_id) {
                const where = [
                    ['site_id', '=', site_id]
                ];
                return this.model.where(where).column('role_name', 'role_id');
  }

  /**
   * getColumn
   * 对应 PHP: RoleService_admin::getColumn()
   * 逻辑类型: undefined - undefined
   */
  async getColumn(site_id: number) {
    // 基于PHP真实逻辑: getColumn
    // PHP原文: $cache_name = 'role_column_'.$site_id;         return cache_remember(             $cache_name,             function() use($site_id) {                 ...
const cache_name = 'role_column_'.site_id;
        return cache_remember(
            cache_name,
            function() use(site_id) {
                const where = [
                    ['site_id', '=', site_id]
                ];
                return this.model.where(where).column('role_name', 'role_id');
  }

  /**
   * getMenuIdsByRoleIds
   * 对应 PHP: RoleService_admin::getMenuIdsByRoleIds()
   * 逻辑类型: undefined - undefined
   */
  async getMenuIdsByRoleIds(site_id: any[], role_ids: any[]) {
    // 基于PHP真实逻辑: getMenuIdsByRoleIds
    // PHP原文: $menu_keys = (new SiteService())->getMenuIdsBySiteId($site_id, 1);         $allow_role_ids = array_merge($role_ids, $menu_keys);         sort($allow_r...
const menu_keys = this.siteService.getMenuIdsBySiteId(site_id, 1];
        const allow_role_ids = Object.assign(role_ids, menu_keys];
        sort(allow_role_ids);
        const cache_name = 'user_role_'.site_id + '_'.md5(implode('_', allow_role_ids)];
        return cache_remember(
            cache_name,
            function() use(role_ids, menu_keys) {
                const rules = this.model.where([['role_id', 'IN', role_ids], ['status', '=', RoleStatusDict.ON))).field('rules').select().toArray(];
                if(!!rules)){
                    const temp = [];
                    foreach(rules as k => v){
                        const temp = Object.assign(temp, v.rules];
                    }
                    const temp = array_unique(temp);
                    if(!menu_keys)) return [];
                    if(!temp)) return [];
                    return array_intersect(temp, menu_keys];
                }
                return [);
  }
}
